__author__ = "liwen"
__time__ = "上午9:48"

from fastapi import APIRouter,File, UploadFile,status, HTTPException
from typing import Optional, List
import os
from ..UserService.models import UserOut, UserIn




file = APIRouter()

# 适合小文件
@file.get("/file")
def get_file(file:bytes=File(...)):
    return {"file":file}


@file.get("/files")
def get_files(files:List[bytes]=File(...)):

    return {"file":files}


@file.get("/uploadFile")
async def get_uploadFile(files:List[UploadFile]=File(...)):
    """
        使用uploadFile类的优势
        1.文件存在内存中，内存满了之后，将保存在磁盘中
        2.适合于图片、视频大文件
        3.可以获得上传的文件的元数据，如文件名，创建时间等
        :param files:
        :return:
        """
    for file in files:
        contents = await file.read()
        print(file.filename)
        print(file.content_type)

        path = os.path.join("imgs", file.filename)
        # with open(path, "wb") as f:
        #     for i in file:
        #         f.write(i)
    return {"file":files}


@file.post(
    "path_operation",
    response_model=UserOut,
    tags = ["Path", "Operation", ],
    summary="this is summary",
    description="this is description",
    response_description="response_description",
    deprecated=True,
    status_code=status.HTTP_200_OK
)
async def path_operation(user: UserIn):
    """
    路径操作配置
    :param user:
    :return:
    """
    return user.dict()

@file.get("/http_exception")
async def http_exception(name: str):
    if name != "Beijing":
        raise HTTPException(status_code=404, detail="no found",headers={"X-Error":"error"})
    return {"name":name}
